import axios from 'axios'
import Vue from 'vue';
import qs from 'qs'
import { Toast, Dialog } from 'vant'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'
import Cookies from 'js-cookie'
import { getUserInfo } from './localStorage'
import error from '@/components/error/error.vue'

// 创建一个axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // withCredentials: true,
  timeout: 20000
})
const whiteRouter=['/cart/changeNum','/orderQg/cartList','/cart/changeNum','/order/statusCount']
// 请求拦截器
service.interceptors.request.use(
  config => {
    // console.log('config==',config)
    if (config.url.includes('registry') || config.url.includes('argeement') || config.url.includes('login')) {
      return config
    }
    if (getToken()&&getToken()!=null) {
      config.headers.Authorization = getToken()
    }
    console.log(config.method)
    console.log((config.method === 'post' || config.method === 'put') && config.url!=='/cart/changeNum' && config.url!='/orderQg/cartList' && !config.url.includes('cart/changeNum'))
    if ((config.method === 'post' || config.method === 'put') && !whiteRouter.includes(config.url)) {
      const requestObj = {
        url: config.url,
        data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
        time: new Date().getTime()
      }
      let sessionObj = sessionStorage.getItem('sessionObj')
      sessionObj =JSON.parse(sessionObj)
      if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
        sessionStorage.setItem('sessionObj',JSON.stringify(requestObj))
        // cache.session.setJSON('sessionObj', requestObj)
      } else {
        const s_url = sessionObj.url;                  // 请求地址
        const s_data = sessionObj.data;                // 请求数据
        const s_time = sessionObj.time;                // 请求时间
        const interval = 5000;                         // 间隔时间(ms)，小于此时间视为重复提交
        if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
          const message = '数据正在处理，请勿重复提交';
          console.warn(`[${s_url}]: ` + message)
          return false
        } else {
          // cache.session.setJSON('sessionObj', requestObj)
          sessionStorage.setItem('sessionObj',JSON.stringify(requestObj))

        }
      }
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    // console.log(response)
    const res = response.data
    if(getUserInfo().mobile!== null &&  getUserInfo().password!== null){
      if(!sessionStorage.getItem('token') || !localStorage.getItem('token')){
        store.dispatch('user/login',getUserInfo())

      }
    }
    // 返回码不正确
    if (res.code !== 200) {
      // 5001订单不存在
      // if (res.code !== 5001) {
      //   Toast.fail(res.msg)
      // }
      // 401未登陆 || res.code ==500
      if (res.code == 401 ) {
        if(getToken()){
          sessionStorage.clear()
          localStorage.removeItem('token')
          // if(!sessionStorage.getItem('token')){
            // router.go(0)
            router.push({ name: 'Login' })

          // }
        }else{
          // Dialog.alert({
          //   title: '提示',
          //   message: '您还未登录，请登录'
          // }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              router.push({ name: 'Login' })
            })
          // })
        }
        return
      }
      // 订单轮询
      if (res.code === 5001) {
        Toast.fail(res.msg)
        return Promise.reject(new Error(res.msg || 'Error'))
      }
      Toast.fail(res.msg)
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    // Vue.prototype.$errorImg = true
    // store.commit('user/SET_ERROR_IMG',Vue.prototype.$errorImg)
    Toast.fail(error.message)

    return Promise.reject(error)
  }
)

/**
 * 使用 application/x-www-form-urlencoded format
 * @param {*} url
 * @param {*} postData
 * @returns
 */
service.formDataPost = function(url, postData) {
  const options = {
    method: 'POST',
    headers: { 'content-type': 'application/x-www-form-urlencoded' },
    data: qs.stringify(postData),
    url
  }
  return service(options)
}

export default service
